package com.lhy.framework.beans.factory.support;

import com.lhy.framework.beans.BeansException;
import com.lhy.framework.beans.factory.FactoryBean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName FactoryBeanRegistrySupport
 * @Description
 * @Author lihaiyang
 * @Date 2022/9/12 22:48
 * @Version 1.0
 */
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {

    private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>();

    protected Object getCacheObjectForFactroyBean(String beanName) {
        Object object = this.factoryBeanObjectCache.get(beanName);
        return (object != NULL_OBJECT ? object : null);
    }

    protected Object getObjectFromFactoryBean(FactoryBean factoryBean, String beanName) {
        if (factoryBean.isSingleton()) {
            Object object = this.factoryBeanObjectCache.get(beanName);
            if (null == object) {
                object = doGetObjectFromFactoryBean(factoryBean, beanName);
                this.factoryBeanObjectCache.put(beanName, object);
            }
            return (object != NULL_OBJECT ? object : null);
        }
        return doGetObjectFromFactoryBean(factoryBean, beanName);
    }

    private Object doGetObjectFromFactoryBean(FactoryBean factoryBean, String name) {
        try {
            return factoryBean.getObject();
        } catch (Exception e) {
            throw new BeansException("FactoryBean throw exception on object[" + name + "] create", e);
        }
    }

}
